package com.quiz.bis.service.impl;

import com.quiz.bis.domain.model.*;
import com.quiz.bis.mapper.StatMapper;
import com.quiz.bis.service.IStatService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;

@Service
@RequiredArgsConstructor
public class StatServiceImpl implements IStatService {

    private final StatMapper statMapper;

    @Override
    public ExamStatModel getExamStatistics() {
        ExamStatModel model = new ExamStatModel();
        model.setTotalExams(statMapper.countTotalExams());
        model.setPublishedExams(statMapper.countExamsByStatus(1));
        model.setOngoingExams(statMapper.countExamsByStatus(2));
        model.setDraftExams(statMapper.countExamsByStatus(0));
        model.setTypeDistribution(statMapper.getExamTypeDistribution());
        model.setStatusDistribution(statMapper.getExamStatusDistribution());
        model.setDurationDistribution(statMapper.getExamDurationDistribution());
        return model;
    }

    @Override
    public PaperStatModel getPaperStatistics() {
        PaperStatModel model = new PaperStatModel();
        model.setTotalPapers(statMapper.countTotalPapers());
        model.setActivePapers(statMapper.countPapersByStatus(1));
        model.setArchivedPapers(statMapper.countPapersByStatus(2));
        model.setTopUsedPapers(statMapper.getTopUsedPapers(10));
        model.setDifficultyDistribution(statMapper.getPaperDifficultyDistribution());
        model.setPassRateDistribution(statMapper.getPaperPassRateDistribution());

        // 计算最近30天的平均分趋势
        Calendar calendar = Calendar.getInstance();
        Date endDate = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, -30);
        Date startDate = calendar.getTime();
        Double avgScoreTrend = statMapper.getAvgScoreTrend(startDate, endDate);
        if(avgScoreTrend == null){
            avgScoreTrend = 0.0;
        }
        model.setAvgScoreTrend(avgScoreTrend);

        return model;
    }

    @Override
    public QuestionStatModel getQuestionStatistics() {
        QuestionStatModel model = new QuestionStatModel();
        model.setTotalQuestions(statMapper.countTotalQuestions());
        model.setActiveQuestions(statMapper.countActiveQuestions());
        model.setTopUsedQuestions(statMapper.getTopUsedQuestions(20));
        model.setTypeDistribution(statMapper.getQuestionTypeDistribution());
        model.setDifficultyDistribution(statMapper.getQuestionDifficultyDistribution());
        model.setCorrectnessDistribution(statMapper.getQuestionCorrectnessDistribution());
        return model;
    }
}